package serveur;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.log4j.Logger;

public class ThreadDialogue2 implements Runnable {

	private final static Logger logger = Logger.getLogger(ThreadDialogue.class);

	PrintWriter out;
	BufferedReader in;
	static Socket socket;
	ServerSocket serveurSocket;
	String ip;
	int port = 0;
	int numero;

	public ThreadDialogue2(int j, ServerSocket serveurSocket) {
		this.numero = j;
		this.serveurSocket = serveurSocket;

	}

	public void run() {
		while (true) {
			System.out.println(numero + "-> en attente d'une connexion...");
			logger.info("Serveur en attente de connexion d'un client");
			try {
				socket = serveurSocket.accept();
				ip = socket.getInetAddress().getHostAddress();
				port = socket.getPort();
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			} catch (IOException e) {
				e.printStackTrace();
			}
			out.println("Connexion TCP etablie");
			logger.info("Connexion d'un client : " + ip + ":" + port);

			System.out.println(numero + "-> connexion TCP etablie");

			String message = "";
			boolean continuer = true;
			while (continuer == true) {
				try {
					// Lecture
					message = in.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println(message);
				String text = "";
				// Interpretation de la requete
				if (getTypeRequete(message).equals("GET")) {
					if (verifierRequeteGet(message)) {
						String[] requete = message.split(" ");
						String nomFichier = "";
						if (requete[1].equals("/")) {
							nomFichier = "index.html";
						} else {
							nomFichier = requete[1].replaceAll("/", "");
						}
						File fichier = new File(nomFichier);
						if (fichier.exists()) {
							try {
								// text = _GET(message, out);
								text = _GET2(message, out);
							} catch (IOException e) {
								e.printStackTrace();
							}
							text = text + "\n <CR> <LF>";
						} else {
							text = "HTTP/1.1 404 Not Found \n <CR> <LF>";
							logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
						}
					} else {
						text = "HTTP/1.1 400 Bad Request \n <CR> <LF>";
						logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
					}
				} else if (message.equalsIgnoreCase("FIN")) {
					continuer = false;
				} else {
					logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);

				}
				out.println(text);
			}
			logger.info("Fermeture de la connexion avec le client : " + ip + ":" + port);
			System.out.println(numero + "-> fermeture de la connexion du client");
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			out.close();
		}
	}

	private String _GET2(String message, PrintWriter out2) throws UnsupportedEncodingException, IOException {
		String text = "";
		String[] requete = message.split(" ");
		String nomFichier = "";
		if (requete[1].equals("/")) {
			nomFichier = "index.html";
		} else {
			nomFichier = requete[1].replaceAll("/", "");
		}
		System.out.println("--->" + nomFichier);
		File fichier = new File(nomFichier);
		double taille = fichier.length();
		if (fichier.exists()) {
			BufferedReader br = null;
			String ligne = "";
			text = "HTTP/1.1 200 OK \n";
			logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
			text = text + "Content-length: " + taille + "\n";
			Path path = Paths.get(nomFichier);
			text = text + new String(Files.readAllBytes(path), "UTF-8");
		}
		return text;

	}

	private String _GET(String message, PrintWriter out) throws IOException {
		String text = "";
		String[] requete = message.split(" ");
		File fichier = new File(requete[1]);
		String nomFichier = requete[1];
		double taille = fichier.length();
		if (fichier.exists()) {
			BufferedReader br = null;
			String ligne = "";
			text = "HTTP/1.1 200 OK \n";
			logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
			text = text + "Content-length: " + taille + "\n";
			br = new BufferedReader(new FileReader(nomFichier));
			while ((ligne = br.readLine()) != null) {
				text = text + ligne + "\n";
			}
		}
		return text;
	}

	private static String getTypeRequete(String message) {
		return message.split(" ")[0];
	}

	private static boolean verifierRequeteGet(String message) {
		boolean verification = false;
		String[] requete = message.split(" ");
		if (requete.length >= 3) {
			if (requete[0].equals("GET") && (requete[2].equals("HTTP/1.1") || requete[2].equals("HTTP/1.0"))) {
				verification = true;
			}
		}
		return verification;
	}
}
